package com.isoft.controller.sys;

import com.isoft.bean.Result;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.isoft.anno.SysControllerLogAnnotation;
import com.isoft.bean.OprateType;
import com.isoft.bean.ResponseData;
import com.isoft.bean.SysType;
import com.isoft.bean.UserContext;
import com.isoft.controller.BaseController;
import com.isoft.dao.UserDao;
import com.isoft.entity.User;
import com.isoft.service.IUserService;
import com.isoft.util.AliOSSUtils;
import com.isoft.util.JwtUtils;
import com.isoft.util.PwdSaltUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@CrossOrigin
@RequestMapping("/sys/user")
public class UserController extends BaseController {
    @Autowired
    IUserService userService;
    @Autowired
    AliOSSUtils aliOSSUtils;
    @Autowired
    UserDao userDao;

    //登录
    @SysControllerLogAnnotation(sysType = SysType.GENERAL, operateType = OprateType.LOGIN, desc = "登录")
    @GetMapping("/login")
    public ResponseData<User> login(String name, String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {
//        if (name.equals("admin")) UserContext.setCurrentUserType(SysType.SUPER.getName());
//        if (name.equals("assessor")) UserContext.setCurrentUserType(SysType.SYSTEM.getName());
//        if (name.equals("common")) UserContext.setCurrentUserType(SysType.GENERAL.getName());
        if(userDao.isAdmin(name) != null && userDao.isAdmin(name).size() != 0) {
            UserContext.setCurrentUserType(SysType.SUPER.getName());
            System.out.println("super");
        }
        else if(userDao.isAssessor(name) != null && userDao.isAssessor(name).size() != 0)
        {
            UserContext.setCurrentUserType(SysType.SYSTEM.getName());
            System.out.println("SYSTEM");
        }
        else if(userDao.isCommon(name) != null && userDao.isCommon(name).size() != 0)
        {
            UserContext.setCurrentUserType(SysType.GENERAL.getName());
            System.out.println("GENERAL");
        }
        else
        UserContext.setCurrentUserType("不明用户");
//        User user = userService.getUserLogin(name, password);
        ResponseData<User> responseData = new ResponseData<>();
        User user=userDao.selectByName(name);
        if(user==null){
            responseData.setErrorCode("503");
            responseData.setMsg("账号或密码错误");
            return responseData;
        }else {
            String salt=user.getSalt();
            String passwordInDb=user.getPassword();
            if(PwdSaltUtil.validPassword(password,salt,passwordInDb)){
                Map<String, Object> claims = new HashMap<>();
                claims.put( "id",user.getId() );
                claims.put( "username",user.getName());
                String jwt = JwtUtils.generateJwt( claims );
                user.setToken(jwt);
                user.setEmail(null);
                user.setIdentifyingCode(null);
                user.setPassword(null);
                user.setAddress(null);
                user.setSalt(null);
                user.setIslock(null);
                user.setPhone(null);
                responseData.setData(user);
                responseData.setErrorCode("200");
                responseData.setMsg("登录成功");
            }
            return responseData;
        }
    }

    //用户修改个人信息
    @SysControllerLogAnnotation(sysType = SysType.GENERAL, operateType = OprateType.UPDATE, desc = "用户修改个人信息")
    @PutMapping("/update")
    public ResponseData<Boolean> update(@RequestBody User User) {
        return returnBoolean(userService.updateById(User));
    }
    //修改个人密码
    @SysControllerLogAnnotation(sysType = SysType.GENERAL, operateType = OprateType.UPDATE, desc = "修改个人密码")
    @PutMapping("/updatePwd")
    public ResponseData<Boolean> updatePwd( Integer id ,String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        return returnBoolean(userService.updatePwd(id,password));
    }
    //注册
    @SysControllerLogAnnotation(sysType = SysType.GENERAL, operateType = OprateType.INSERT, desc = "新用户注册")
    @PostMapping("/adds")
    public Result add(@RequestBody User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String salt = PwdSaltUtil.getSalt();
        String pwd=PwdSaltUtil.getEncryptedPwd(user.getPassword(),salt);
        user.setSalt(salt);
        user.setPassword(pwd);
        Integer addUser = userService.add(user);
        if (addUser == 0) {
            return Result.success();
        } else if (addUser == 1) {
            return Result.error("请输入用户信息！");
        } else if (addUser == 2) {
            return Result.error("用户名不能为空！");
        } else if (addUser == 3) {
            return Result.error("验证码已过期！");
        } else {
            return Result.error("验证码输入有误！");
        }
    }


    @GetMapping("/gets")
    public Result<IPage<User>> selectAll(Integer currentPage, Integer size) {
        Result<IPage<User>> result=new Result<>();
        result.setData(userService.selectAll(currentPage,size));
        return result;
    }

    @GetMapping("getsbyid")
    public ResponseData<Object> getsByid(Integer id) {
        return returnObject(userService.selById(id));
    }
    //管理员管理用户--删除用户
    @SysControllerLogAnnotation(sysType = SysType.SUPER, operateType = OprateType.DELETE, desc = "删除用户")
    @DeleteMapping("/delete")
    public ResponseData<Boolean> deleteById(Integer id) {
        return returnBoolean(userService.deleteById(id));
    }
    //用户修改个人头像
    @SysControllerLogAnnotation(sysType = SysType.GENERAL,operateType = OprateType.UPDATE,desc="用户修改头像")
    @PostMapping("/updatephoto")
    public ResponseData<Boolean> updatePhoto(Integer id,String photourl){
        return returnBoolean(userService.updatePhoto(id,photourl));
    }
    //阿里修改头像测试
    @PostMapping("/updatehead")
    public ResponseData<Object> updatehead(@RequestParam("id") Integer id, @RequestParam("image") MultipartFile file) throws IOException {
        System.out.println("Received id: " + id);
        System.out.println("Received file: " + (file != null ? file.getOriginalFilename() : "null"));
        if (file == null || file.isEmpty()) {
            return new ResponseData<>("400", "文件不能为空", null);
        }
        String url = aliOSSUtils.upload(file);
        userService.updatehead(id, url);
        return returnObject(url);
    }

    @GetMapping("/identifyingCode")
    public Result getIdentifyingCode(String email) {
        String IdentifyingCode = userService.getIdentifyingCode(email);
        return Result.success(IdentifyingCode);
    }
    @PutMapping("/updateIdeAddPhone")
    public ResponseData<Boolean> updateIdeAddPhone(@RequestBody User User) {
        return returnBoolean(userService.updateIdeAndAddressAndPhone(User));
    }
}
